package cn.epsilon3.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.epsilon3.common.ResultResp;
import cn.epsilon3.constant.ResultEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Security token统一拦截器
 */
@Component
public class SecurityTokenInterceptor implements HandlerInterceptor {

    private static final Log log = LogFactory.get();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        boolean isLogin = StpUtil.isLogin();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        if (isLogin) {
            try {
                StpUtil.checkActivityTimeout();
            } catch (NotLoginException notLoginException) {
                ResultResp.resp(response,
                        ResultEnum.AUTH_EXPIRED.getCode(),
                        ResultEnum.AUTH_EXPIRED.getMessage());
                return false;
            }
            return true;
        } else {
            ResultResp.resp(response,
                    ResultEnum.AUTH_EXPIRED.getCode(),
                    ResultEnum.AUTH_EXPIRED.getMessage());
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }



}

